<template>
  <div id="app">
    <top-nav></top-nav>
    <transition enter-active-class="animate__animated animate__backInLeft">
      <router-view @play="play" @playall="playall"></router-view>
    </transition>
    <!-- 调用播放组件 -->
    <transition enter-active-class="animate__animated animate__slideInLeft">
      <music-play
        v-if="music"
        :music="music"
        :playCollect="playCollect"
        @changemusic="changeMusic"
        @changecircle="changecircle"
        :cirlceMode="cirlceMode"
        @play="play"
        @changeSong="changeSong"
      ></music-play>
    </transition>
  </div>
</template>
<script>
import TopNav from "@/components/TopNav.vue";
import MusicPlay from "@/components/MusicPlay.vue";

export default {
  components: {
    TopNav,
    MusicPlay,
  },
  data() {
    return {
      music: null,
      playCollect: [], 
      cirlceMode: "list", //list 列表循环, single单曲循环 random随机播放
    };
  },
  methods: {
    play(song) {
      this.music = song; 
      let isExit = false;
      for (let i = 0; i < this.playCollect.length; i++) {
        if (this.playCollect[i].id == song.id) {
          isExit = true;
          break;
        }
      }
      if (isExit) {
        // alert("该歌曲已经存在播放列表!");
      } else {
        this.playCollect.push(song);
      }
    },
    changeSong(item){
      this.music = item;
    },
    changeMusic(i) {
      let currentIndex = 0;
      this.playCollect.forEach((item, index) => {
        if (item.id == this.music.id) {
          currentIndex = index; 
        }
      });
      if (this.cirlceMode == "single") {
        //单曲循环
        this.music = { ...this.playCollect[currentIndex] }; 
        return;
      } else if (this.cirlceMode == "random") {
        //随机播放
        let random = Math.random() * this.playCollect.length; 
        random = Math.floor(random);
        this.music = this.playCollect[random];
        return;
      }
      if (i == 1) {
        currentIndex--;
        if (currentIndex < 0 && !this.playCollect[currentIndex]) {
          currentIndex = this.playCollect.length - 1;
        }
      } else if (i == 2) {
        currentIndex++;
        if (
          currentIndex > this.playCollect.length - 1 &&
          !this.playCollect[currentIndex]
        ) {
          currentIndex = 0;
        }
      }
      this.music = this.playCollect[currentIndex];
    },
    playall(songs) {
      this.playCollect = songs;
      this.music = songs[0];
    },
    changecircle(circle) {
      this.cirlceMode = circle;
    }
  },
};
</script>
<style lang="less">
html,
body,
#app {
  height: 100%;
}
</style>
